<template>
  <div class="drawer_box">
    <div class="flex_bw_center" style="transform: translate(-1px, 1px)"></div>
    <div class="isTable flex_start_start">
      <div class="date_searchbox">
        <div>
          <el-date-picker
            style="width: 218px"
            v-model="value3"
            type="month"
            value-format="YYYY-MM"
            placeholder="选择月份"
            @change="chanse"
          />
        </div>
        <div class="month_box">
          <div
            @click="itemClick(index, item)"
            class="items flex_center_center"
            v-for="(item, index) in dateArr"
            :key="index"
            :class="{ isDate: item.is }"
          >
            {{ item.date }}
          </div>
        </div>
      </div>

      <div style="width: 88%; height: 726px; overflow-y: scroll">
        <div
          v-for="(items, indexs) in bigArr"
          :key="indexs"
          style="
            width: 100%;
            height: 150px;
            margin-bottom: 30px;
            padding: 10px;
            box-sizing: border-box;
          "
        >
          <div class="title">{{ items.orgName }}</div>
          <el-table
            :data="list"
            border
            fit
            highlight-current-row
            stripe
            height="104"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              align="center"
              width="60"
              label="序号"
            >
            </el-table-column>
            <el-table-column label="值班日期" align="center">
              <template #default="scope">
                <span>{{ scope.row.date }}</span>
              </template>
            </el-table-column>

            <el-table-column
              v-show="items.children.length"
              v-for="(item, index) in items.children"
              :key="index"
              :label="getLabel(item)"
              align="center"
            >
              <el-table-column
                show-overflow-tooltip
                :label="it.name"
                align="center"
                v-for="it in item.children"
                :key="it.id"
              >
                <template #default="scope">
                  <div>
                    {{ textData(scope.row, it.id) }}
                  </div>
                </template>
              </el-table-column>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import http from "@/utils/api";
import {
  Search,
  Share,
  Upload,
  TakeawayBox,
  Refresh,
  Collection,
  Plus,
  Loading,
  FolderDelete,
  Back,
} from "@element-plus/icons-vue";
import {
  ref,
  watch,
  onMounted,
  onBeforeUnmount,
  reactive,
  onBeforeMount,
  nextTick,
  onUnmounted,
} from "vue";
import { defineProps, defineEmits } from "vue";
const activeName = ref("普管级");
const props = defineProps({
  sonData: {
    type: String,
    default: "",
  },
  jqArr: {
    type: Array,
    default: [],
  },
});
let list = ref([]);
const selectValue = ref("");
let dateSfm = ref("");
let hour = ref("");
let daydata = ref("");
let years = ref("");
let value3 = ref("");
let months = ref("");
let dateArr = ref([]);
let days = ref('')
let jqArr = ref([]);
onBeforeMount(async () => {});
// 获取年月日 时
const getFormattedDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  const hours = String(now.getHours()).padStart(2, "0");
  const minutes = String(now.getMinutes()).padStart(2, "0");
  const seconds = String(now.getSeconds()).padStart(2, "0");
  dateSfm.value = `${hours}:${minutes}:${seconds}`;
  hour.value = String(now.getHours()).padStart(2, "0");
  daydata.value = `${year}-${month}-${day}`;
  years.value = `${year}`;
  months.value = `${month}`;

  return `${year}-${month}-${day} ${hour.value}`;
};
let classList = ref([]);
let pids = ref(0);
let bigArr = ref([]);
const getShiftSelect = async () => {
  bigArr.value = [];
  classList.value = []
  let resz = await http.znjw.ShiftSelect({
    type: "jq",
    pId: 0,
    orgId: selectValue.value || "",
    startDate: "",
    endDate: "",
    isLock: 0,
    zbType: "1",
  });
  if (resz.code == 0) {
    if (resz && resz.data[0]?.children.length) {
      bigArr.value = resz.data;
      classList.value = resz.data[0].children;
      pids.value = resz.data[0].id;
    } else {
      classList.value = [];
    }
    getList();
  }
};
let listData = ref([]);
const getList = async () => {
  let dateArr = [years.value, months.value];
  let dateObj = new Date(dateArr[0], dateArr[1], 0);
  let MonthNum = dateObj.getDate();

  for (let i = 0; i <= bigArr.value.length; i++) {
    try {
      let res = await http.znjw.ZdbSelect({
        type: "jq",
        zbType: "1",
        orgId: bigArr.value[i].orgId || "",
        shift: bigArr.value[i].id,
        account: "",
        date: days.value,
      });
      listData.value.push(...res.data); // 将结果存储到 results 数组中
      for (let i = 1; i <= MonthNum; i++) {
        let obj = {
          date: dealTime(`${dateArr[0]}-${dateArr[1]}-${i <= 9 ? "0" + i : i}`),
          type: "jq",
          zbType: 1,
          shift: 0,
          shiftArr: [],
        };

        //日期匹配数据
        let newArr = res.data.filter((item) => dealTime(item.date) == obj.date);

        if (newArr.length) {
          //多个班次数据合并
          let newsToOne = {
            date: dealTime(newArr[0].date),
            type: "jq",
            zbType: 1,
            shift: newArr[0].shift,
            shiftArr: [],
          };
          newArr.forEach((ele) => {
            let item = {
              zhz: ele.zhz,
              zbry: ele.zbry,
              zbz: ele.zbz,
              shift: ele.shift,
              zbryAccount: ele.zbryAccount,
              zhzAccount: ele.zhzAccount,
              zbzAccount: ele.zbzAccount,
            };
            newsToOne.shiftArr.push(item);
          });
          list.value[i - 1] = newsToOne;
        } else {
          list.value[i - 1] = obj;
        }
      }
    } catch (error) {
      console.error("Error fetching data:", error);
      // 如果需要处理错误，可以在这里添加逻辑
    }
  }

  // listData.value = res.data;

  list.value = list.value.filter((item) => item.date == days.value);
};
const dealTime = (date, format) => {
  if (date) {
    return date.split("T")[0];
    // return format
    //   ? new Date(date).Format(format)
    //   : new Date(date).Format("yyyy-MM-dd");
  }
};

const getLabel = (row) => {
  let str = "";
  str = row.name + " " + row.start + "-" + row.end;

  return str;
};
const textData = (row, Ltid) => {
  // console.log(row, Ltid, "ppppppp", listData.value);

  let str = "";
  listData.value.forEach((item) => {
    if (item.shift == Ltid) {
      if (row.date == item.date.split("T")[0]) str = item.zbry;
    } else {
      return false;
    }
  });
  return str;
};
const chanse = (row) => {
  if (row) {
    years.value = `${row.split("-")[0]}`;
    months.value = `${row.split("-")[1]}`;
    getMonthDates();
  } else {
  }
};

const getMonthDates = () => {
  const now = new Date();
  const year = Number(years.value);
  const month = Number(months.value); // 注意：月份从0开始，所以11表示12月
  // 获取当前月的天数
  const daysInMonth = new Date(year, month, 0).getDate();
  // 生成日期数组
  const dates = [];
  for (let day = 1; day <= daysInMonth; day++) {
    const dateString = `${year}-${String(month).padStart(2, "0")}-${String(
      day
    ).padStart(2, "0")}`;
    dates.push({
      date: dateString,
      is: false,
    });
  }

  dateArr.value = dates;
  dateArr.value.forEach((item) => {
    if (item.date == daydata.value) {
      item.is = true;
    }
  });
};


const itemClick = (index, item) => {
  dateArr.value.forEach((item) => {
    item.is = false;
  });
  days.value = item.date;
  // value3.value = item.date;
  getShiftSelect();
  dateArr.value[index].is = true;
};

watch(
  () => props.jqArr,
  (newValue, oldValue) => {
    getFormattedDateTime();
    if (newValue) {
      getMonthDates();
      value3.value = daydata.value;
      days.value = daydata.value;
      if (props.jqArr) {
        selectValue.value = props.jqArr.map((itz) => itz.id).join(",");
      }
      getShiftSelect();
      //;
    } else {
    }
  },
  {
    deep: true, // 深度监听
    immediate: true, // 立即触发回调
  }
);
</script>

<style scoped lang="scss">

::v-deep .date_searchbox {
  .el-input__wrapper {
    background-color: rgba(15, 82, 163, 0.278);
    box-shadow: (0 0 0 1px rgba(15, 82, 163, 0.61)) inset;
  }
  .el-input__inner {
    color: white;
  }
  .el-input__prefix {
    color: white;
  }
}

.title {
  text-align: center;
  color: white;
  font-size: 16px;
  margin-bottom: 6px;
}
.isDate {
  color: #ffffff;
  font-weight: bold;
  border-color: rgb(18, 123, 215) !important;
  // background-color: #e9e9e9ea !important;
}
.isAtv {
  background-color: rgb(4 110 250 / 27%) !important;
  font-weight: bold;
}
.date_searchbox {
  width: 220px;
  height: 100%;
  // border: 1px solid red;
  margin-right: 6px;
  .month_box {
    width: 100%;
    height: 726px;

    overflow-y: scroll;
    margin-top: 4px;
    .items {
      font-size: 14px;
      width: 100%;
      margin-bottom: 4px;
      cursor: pointer;
      height: 24px;
      color: #fff;
      border-bottom: 1px solid rgba(15, 82, 163, 0.61);
      // background-color: #e9e9e979;
    }
  }
}

.isAtv {
  background-color: rgb(4 110 250 / 27%) !important;
  font-weight: bold;
}
::v-deep .isTable .el-table {
  background-color: rgb(8, 32, 78) !important;
  .el-table tr {
    background-color: rgb(8, 32, 78) !important;
  }
  .cell {
    height: 30px;
    color: #fff;
    text-align: center;
    // border: 1px solid #ccc;
    background: rgb(8, 32, 78) !important;
    font-size: 12px;
    line-height: 30px;
  }
  .el-table__cell {
    border-color: 1px solid rgb(5, 112, 146);
    padding: 2px 0px !important;
    background: rgb(8, 32, 78) !important;
  }
  .el-table--fit .el-table__inner-wrapper:before {
    display: none !important;
  }
  .el-table th.el-table__cell.is-leaf {
    border: none !important;
  }
  --el-table-border-color: rgb(5, 112, 146);
}
.drawer_box {
  width: 100%;
  height: 100%;
  position: relative;
  padding: 0 10px;
  box-sizing: border-box;
  overflow: hidden;
  .drawer_text {
    position: absolute;
    top: -23px;
    left: 2px;
    font-size: 18px;
  }
}
</style>
